package com.ship.boats.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ship.boats.business.impl.BoatsSystemServiceImpl;
import com.ship.boats.domain.SpBoatsIhsInspectionsCertificates;
import com.ship.boats.domain.SpBoatsInspectionsDefects;
import com.ship.boats.domain.SpBoatsPscInspect;
import com.ship.boats.domain.dto.BoatsPscInspectRq;
import com.ship.boats.domain.dto.ExportInspectionsRq;
import com.ship.boats.domain.dto.ExportPscInspectRq;
import com.ship.boats.domain.dto.QueryPscInspectRq;
import com.ship.boats.domain.vo.QueryInspectionDetailsInfo;
import com.ship.boats.domain.vo.QueryInspectionsCertificatesInfo;
import com.ship.boats.domain.vo.QueryInspectionsDefectsInfo;
import com.ship.boats.domain.vo.QueryPscInspectInfo;
import com.ship.boats.mapper.SpBoatsPscInspectMapper;
import com.ship.boats.service.BoatsArchivesService;
import com.ship.boats.service.SpBoatsIhsInspectionsCertificatesService;
import com.ship.boats.service.SpBoatsInspectionsDefectsService;
import com.ship.boats.service.SpBoatsPscInspectService;
import com.ship.common.core.base.Page;
import com.ship.common.core.constant.ShipApiConstants;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>SpBoatsPscInspectServiceImpl</b>
 *
 * @description: SpBoatsPscInspectServiceImpl <br>
 * @date: 2024/3/21 09:53 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class SpBoatsPscInspectServiceImpl implements SpBoatsPscInspectService {
    private static final Logger logger = LoggerFactory.getLogger(SpBoatsPscInspectServiceImpl.class);

    @Autowired
    private SpBoatsPscInspectMapper spBoatsPscInspectMapper;

    @Autowired
    private SpBoatsIhsInspectionsCertificatesService spBoatsIhsInspectionsCertificatesService;

    @Autowired
    private SpBoatsInspectionsDefectsService spBoatsInspectionsDefectsService;

    @Autowired
    private BoatsArchivesService boatsArchivesService;

    @Autowired
    private BoatsSystemServiceImpl boatsSystemServiceImpl;

    @Override
    public List<String> queryPscInspect(String queryType) {
        List<String> returnList = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enable","1");
        List<SpBoatsPscInspect> pscInspectList = spBoatsPscInspectMapper.selectList(queryWrapper);
        if ("name".equals(queryType)){
            returnList = pscInspectList.stream().map(SpBoatsPscInspect::getShipName).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        }else if ("imo".equals(queryType)){
            returnList = pscInspectList.stream().map(SpBoatsPscInspect::getImo).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        }else if ("inspectionsType".equals(queryType)){
            returnList = pscInspectList.stream().map(SpBoatsPscInspect::getInspectionsType).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        }else if ("inspectionPortCode".equals(queryType)){
            returnList = pscInspectList.stream().map(SpBoatsPscInspect::getInspectionPortCode).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        }else if ("inspectionPortDecode".equals(queryType)){
            returnList = pscInspectList.stream().map(SpBoatsPscInspect::getInspectionPortDecode).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        }
        return returnList;
    }

    @Override
    public PageInfo<QueryPscInspectInfo> queryPscInspectList(QueryPscInspectRq rq) {
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        String shipName = null;
        String imo = null;
        String inspectionsType = null;
        String inspectionPortCode = null;
        String inspectionPortDecode = null;
        List<String> newShipNameList = null;
        List<String> newImoList = null;
        List<String> newInspectionsTypeList = null;
        List<String> newInspectionPortCodeList = null;
        List<String> newInspectionPortDecodeList = null;
        if (CollectionUtil.isNotEmpty(rq.getShipNameList())){
            if (rq.getShipNameList().size() == 1){
                shipName = rq.getShipNameList().get(0);
            }else {
                newShipNameList = rq.getShipNameList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getImoList())){
            if (rq.getImoList().size() == 1){
                imo = rq.getImoList().get(0);
            }else {
                newImoList = rq.getImoList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getInspectionsTypeList())){
            if (rq.getInspectionsTypeList().size() == 1){
                inspectionsType = rq.getInspectionsTypeList().get(0);
            }else {
                newInspectionsTypeList = rq.getInspectionsTypeList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getInspectionPortCodeList())){
            if (rq.getInspectionPortCodeList().size() == 1){
                inspectionPortCode = rq.getInspectionPortCodeList().get(0);
            }else {
                newInspectionPortCodeList = rq.getInspectionPortCodeList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getInspectionPortDecodeList())){
            if (rq.getInspectionPortDecodeList().size() == 1){
                inspectionPortDecode = rq.getInspectionPortDecodeList().get(0);
            }else {
                newInspectionPortDecodeList = rq.getInspectionPortDecodeList();
            }
        }
        List<QueryPscInspectInfo> pscInspectList = spBoatsPscInspectMapper.queryPscInspectList(shipName,imo,inspectionsType,inspectionPortCode,inspectionPortDecode,newShipNameList,newImoList,newInspectionsTypeList,newInspectionPortCodeList,newInspectionPortDecodeList,null);
        logger.info("查询PSC检查记录列表返回结果:{}"+ JSONUtil.parse(pscInspectList));
        PageInfo<QueryPscInspectInfo> pageInfo = new PageInfo<>(pscInspectList);
        return pageInfo;
    }

    @Override
    public List<QueryPscInspectInfo> exportPscInspect(ExportPscInspectRq rq) {
        String shipName = null;
        String imo = null;
        String detectionType = null;
        String inspectionPortCode = null;
        String inspectionPortDecode = null;
        List<String> newShipNameList = null;
        List<String> newImoList = null;
        List<String> newDetectionTypeList = null;
        List<String> newInspectionPortCodeList = null;
        List<String> newInspectionPortDecodeList = null;
        if (CollectionUtil.isNotEmpty(rq.getShipNameList())){
            if (rq.getShipNameList().size() == 1){
                shipName = rq.getShipNameList().get(0);
            }else {
                newShipNameList = rq.getShipNameList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getImoList())){
            if (rq.getImoList().size() == 1){
                imo = rq.getImoList().get(0);
            }else {
                newImoList = rq.getImoList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getInspectionsTypeList())){
            if (rq.getInspectionsTypeList().size() == 1){
                detectionType = rq.getInspectionsTypeList().get(0);
            }else {
                newDetectionTypeList = rq.getInspectionsTypeList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getInspectionPortCodeList())){
            if (rq.getInspectionPortCodeList().size() == 1){
                inspectionPortCode = rq.getInspectionPortCodeList().get(0);
            }else {
                newInspectionPortCodeList = rq.getInspectionPortCodeList();
            }
        }
        if (CollectionUtil.isNotEmpty(rq.getInspectionPortDecodeList())){
            if (rq.getInspectionPortDecodeList().size() == 1){
                inspectionPortDecode = rq.getInspectionPortDecodeList().get(0);
            }else {
                newInspectionPortDecodeList = rq.getInspectionPortDecodeList();
            }
        }
        List<QueryPscInspectInfo> pscInspectList = spBoatsPscInspectMapper.queryPscInspectList(shipName,imo,detectionType,inspectionPortCode,inspectionPortDecode,newShipNameList,newImoList,newDetectionTypeList,newInspectionPortCodeList,newInspectionPortDecodeList,rq.getIds());
        logger.info("查询PSC检查记录列表返回结果:{}"+ JSONUtil.parse(pscInspectList));
        return pscInspectList;
    }

    @Override
//    @Transactional
    public void queryCreatePSCInspect() {
        //查询船舶信息imo号
        List<String> boatsList = boatsArchivesService.queryImoList();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-7);
        Date time = calendar.getTime();
        String date = DateUtil.format(time, DatePattern.NORM_DATE_FORMATTER);
        boatsList.forEach(item -> {
            Map<String,String> map = new HashMap<>();
            map.put("imo",item);
            map.put("startDate",date+" 00:00:00");
            Object data = boatsSystemServiceImpl.getBoatsUtil(map, ShipApiConstants.PSC_INSPECT_URL);
            if (null != data){
                List<BoatsPscInspectRq> list = JSONUtil.toList(JSONUtil.parseArray(data), BoatsPscInspectRq.class);
                if (CollectionUtil.isNotEmpty(list)){
                    list.forEach(value -> {
                        SpBoatsPscInspect spBoatsPscInspect = new SpBoatsPscInspect();
                        BeanUtils.copyProperties(value,spBoatsPscInspect);
                        String inspectionsType = "";
                        if (StringUtils.isNotEmpty(value.getExpandedInspection()) && !"False".equals(value.getExpandedInspection())){
                            inspectionsType =inspectionsType + "expand inspection";
                        }
                        if (StringUtils.isNotEmpty(value.getFollowupInspection()) && !"N".equals(value.getFollowupInspection())){
                            inspectionsType =inspectionsType + "followup inspection";
                        }
                        if (StringUtils.isNotEmpty(value.getOtherInspectionType())){
                            inspectionsType =inspectionsType + value.getOtherInspectionType();
                        }
                        spBoatsPscInspect.setInspectionsType(inspectionsType);
                        spBoatsPscInspect.setEnable("1");
                        spBoatsPscInspect.setCreateUser("sys");
                        spBoatsPscInspect.setCreateTime(new Date());
                        spBoatsPscInspect.setUpdateUser("sys");
                        spBoatsPscInspect.setUpdateTime(new Date());
                        if (CollectionUtil.isNotEmpty(value.getIhsInspectionsCertificates())){
                            List<SpBoatsIhsInspectionsCertificates> inspectionsCertificatesList = new ArrayList<>();
                            value.getIhsInspectionsCertificates().forEach(inspectionsCertificates -> {
                                SpBoatsIhsInspectionsCertificates spBoatsIhsInspectionsCertificates = new SpBoatsIhsInspectionsCertificates();
                                BeanUtils.copyProperties(inspectionsCertificates,spBoatsIhsInspectionsCertificates);
                                spBoatsIhsInspectionsCertificates.setInspectionId(value.getInspectionId());
                                inspectionsCertificatesList.add(spBoatsIhsInspectionsCertificates);
                            });
                            boolean status = spBoatsIhsInspectionsCertificatesService.createInspectionsCertificates(inspectionsCertificatesList);
                            if (!status) {
                                throw new ServiceException("保存psc检查证书信息异常！", BaseResultCode.GENERAL_ERROR.getCode());
                            }
                        }
                        if (CollectionUtil.isNotEmpty(value.getIhsInspectionsDefects())){
                            List<SpBoatsInspectionsDefects> inspectionsDefectsList = new ArrayList<>();
                            value.getIhsInspectionsDefects().forEach(inspectionsDefects -> {
                                SpBoatsInspectionsDefects spBoatsInspectionsDefects = new SpBoatsInspectionsDefects();
                                BeanUtils.copyProperties(inspectionsDefects,spBoatsInspectionsDefects);
                                spBoatsInspectionsDefects.setInspectionId(value.getInspectionId());
                                inspectionsDefectsList.add(spBoatsInspectionsDefects);
                            });
                            boolean status = spBoatsInspectionsDefectsService.createInspectionsDefects(inspectionsDefectsList);
                            if (!status) {
                                throw new ServiceException("保存psc检查缺陷信息异常！", BaseResultCode.GENERAL_ERROR.getCode());
                            }
                        }
                        logger.info("保存宝船网PSC检查数据参数:{}" + JSONUtil.parse(spBoatsPscInspect));
                        int insert = spBoatsPscInspectMapper.insert(spBoatsPscInspect);
                        if (insert != 1){
                            throw new ServiceException("保存psc检查信息异常！", BaseResultCode.GENERAL_ERROR.getCode());
                        }
                    });
                }
            }
        });

    }

    @Override
    public QueryInspectionDetailsInfo queryPscInspectById(Long id) {
        return spBoatsPscInspectMapper.queryPscInspectById(id);
    }

    @Override
    public SpBoatsPscInspect queryBoatsInspect(String inspectionId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enable","1");
        queryWrapper.eq("inspection_id",inspectionId);
        return spBoatsPscInspectMapper.selectOne(queryWrapper);
    }

    @Override
    public List<QueryInspectionsCertificatesInfo> InspectionsCertificatesList(ExportInspectionsRq rq) {
        return spBoatsPscInspectMapper.InspectionsCertificatesList(rq);
    }

    @Override
    public List<QueryInspectionsDefectsInfo> queryInspectionsDefectsList(ExportInspectionsRq rq) {
        return spBoatsPscInspectMapper.queryInspectionsDefectsList(rq);
    }

}
